package com.pxmeta.party.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.party.entity.Gift;
import com.pxmeta.party.entity.GiftLottery;
import com.pxmeta.party.mapper.GiftLotteryMapper;
import com.pxmeta.party.mapper.GiftMapper;
import com.pxmeta.party.service.IGiftLotteryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * <p>
 * 语聊派对表 服务实现类
 * </p>
 *
 * @author wcl
 * @since 2022-06-25
 */
@Service
@RequiredArgsConstructor
public class GiftLotteryServiceImpl extends ServiceImpl<GiftLotteryMapper, GiftLottery> implements IGiftLotteryService {
    @Autowired
    private GiftMapper giftMapper;

    @Override
    public void updateGiftLottery(Integer id, Double probability, Integer count, Integer conditionCount, Integer remainingQuantity){
        LambdaQueryWrapper<GiftLottery> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(GiftLottery::getRewardGiftId, id)
                .eq(GiftLottery::getIsProfit, Boolean.TRUE);

        GiftLottery gl = this.getOne(wrapper);
        if (gl != null){
            if (probability!=null){
                gl.setProbability(BigDecimal.valueOf(probability).setScale(2, RoundingMode.HALF_UP));
            }
            if (count !=null){
                gl.setCount(count);
            }
            gl.setConditionCount(conditionCount);
            gl.setRemainingQuantity(remainingQuantity);

            if (gl.getCount()<gl.getRemainingQuantity()){
                gl.setRemainingQuantity(count);
            }
            this.updateById(gl);
        }

    }

    @Override
    public Gift getTreasureChestByRewardGiftId(Integer rewardGiftId) {
        LambdaQueryWrapper<GiftLottery> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(GiftLottery::getRewardGiftId, rewardGiftId)
                .eq(GiftLottery::getIsProfit,Boolean.TRUE);

        GiftLottery giftLottery = this.getOne(wrapper);
        Integer giftId = giftLottery.getGiftId();
        return giftMapper.selectById(giftId);
    }
}
